package com.example.newjiesai.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;

/**
 * 用来进行设置出站解码器和入站编码器
 */
public class TcpInitializer extends ChannelInitializer<SocketChannel> {


    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

        //创建分隔符缓冲对象ByteBuf，以\r\n为分隔符        socket工具与腕表这里可能不一样。后面用腕表可能要改回来
        //ByteBuf delimiter1 = Unpooled.copiedBuffer("\r\n".getBytes());                     //这里\r\n直接表示换行了      new byte[]{0x0d,0x0a}
        ByteBuf delimiter1 = Unpooled.copiedBuffer(new byte[]{0x0d,0x0a});
        //ByteBuf delimiter1 = Unpooled.copiedBuffer("\\r\\n".getBytes());                     //这里将\r\n转义，表示\r\n字符串  new byte[]{0x5C, 0x72, 0x5C, 0x6E}
        pipeline.addLast("decoder", new DelimiterBasedFrameDecoder(                 //处理毡包
                8192,false,delimiter1));

        // 自己的逻辑Handler
        pipeline.addLast("handler", new TcpInboundHandler());           //放在Decoder之后可能导致没有结束符而无法执行channalread方法



    }
}
